﻿using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using MotorcycleStore.Repository;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;
using System.Web.Configuration;
using Ninject.Parameters;
using System;

namespace MotorcycleStore.MVC
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	// http://weblogs.asp.net/shijuvarghese/archive/2010/04/30/dependency-injection-in-nerddinner-app-using-ninject.aspx
	public class MvcApplication : NinjectHttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
				new string[] { "MotorcycleStore.MVC.Controllers" } // Namespaces
			);
		}

		protected override void OnApplicationStarted()
		{
			AreaRegistration.RegisterAllAreas();
			RegisterRoutes(RouteTable.Routes);
			RegisterAllControllersIn(Assembly.GetExecutingAssembly());
		}

		protected override Ninject.IKernel CreateKernel()
		{
			var modules = new INinjectModule[] {
				new ServiceModule()
			};

			return new StandardKernel(modules);
		}
	}

	internal class ServiceModule : NinjectModule
	{
		public override void Load()
		{

			// TODO: Refactor this argument out into an IRepository
			var connectionString = WebConfigurationManager.ConnectionStrings["MotorcycleStoreEntities"].ConnectionString;

			Bind<IMotorcycleRepository>().To<MotorcycleStoreData.EF.MotorcycleRepository>()
				.WithConstructorArgument("connectionString", connectionString);
			Bind<IManufacturerRepository>().To<MotorcycleStoreData.EF.ManufacturerRepository>()
				.WithConstructorArgument("connectionString", connectionString);
			Bind<ICategoryRepository>().To<MotorcycleStoreData.EF.CategoryRepository>()
				.WithConstructorArgument("connectionString", connectionString);

			Bind<IPhotoRepository>().To<MotorcycleStoreData.EF.PhotoRepository>()
				.WithConstructorArgument("connectionString", connectionString);
		}
	}
}